//
//  SunAddEditVC.m
//  Xspcf
//
//  Created by sunshine on 17/5/17.
//  Copyright © 2017年 小小算盘. All rights reserved.
//

#import "SunAddEditVC.h"
#import "IDAddressPickerView.h"

@interface SunAddEditVC ()<UITextFieldDelegate,IDAddressPickerViewDataSource,UIPickerViewDelegate,UITextViewDelegate>
{
    NSMutableDictionary *_addressDic;
    IDAddressPickerView *_picker;
    UIPickerView *_areaPiker;
    NSArray *_cityArr;
    NSArray *_areaArr;
    UITextField *_name;
    UITextField *_phone;
    UITextField *_citys;
    UITextField *_area;
    UITextView *_detail;
    UISwitch *_default;
    int _la;
}
@end

@implementation SunAddEditVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = BACKGROUND;
    self.title = @"收货地址";
    _areaArr = [NSArray array];
    [self createUI];
    // Do any additional setup after loading the view.
}

- (void)createUI{
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, X(50), Y(25))];
    [btn setTitle:@"保存" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(save) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barbutton = [[UIBarButtonItem alloc]initWithCustomView:btn];
    self.navigationItem.rightBarButtonItem = barbutton;
    
    _areaPiker = [[UIPickerView alloc]init];
    _areaPiker.delegate = self;
    
    UIView *view1 = [[UIView alloc]init];
    [self.view addSubview:view1];
    [view1 lt_Top:SunEdgesMake(Y(32), 0, 0, Y(50)) to:nil save:YES];
    view1.backgroundColor = WHITE;
    UIImageView *img1 = [[UIImageView alloc]init];
    [view1 addSubview:img1];
    [img1 lt_YcenterTo:nil save:YES];
    [img1 lt_setLeft:X(15) to:nil save:YES];
    img1.image = [UIImage imageNamed:@"address_1"];
    _name = [[UITextField alloc]init];
    [view1 addSubview:_name];
    [_name lt_YcenterTo:nil save:YES];
    [_name lt_setLeft:X(50) to:nil save:YES];
    [_name lt_setWidth:X(300) save:YES];
    _name.textColor = BLACK;
    _name.font = [UIFont systemFontOfSize:17];
    _name.clearButtonMode = UITextFieldViewModeWhileEditing;
    _name.placeholder = @"请输入姓名";
    _name.delegate = self;
    UIView *view2 = [[UIView alloc]init];
    view2.backgroundColor = WHITE;
    [self.view addSubview:view2];
    [view2 lt_Top:SunEdgesMake(0, 0, 0, Y(50)) to:view1 save:YES];
    UIImageView *img2 = [Sun copyWithView:img1];
    img2.image = [UIImage imageNamed:@"address_2"];
    [view2 addSubview:img2];
    [img2 lt_YcenterTo:nil save:YES];
    [img2 lt_setLeft:X(15) to:nil save:YES];
    _phone = [[UITextField alloc]init];
    [view2 addSubview:_phone];
    [_phone lt_YcenterTo:nil save:YES];
    [_phone lt_setLeft:X(50) to:nil save:YES];
    [_phone lt_setWidth:X(300) save:YES];
    _phone.textColor = BLACK;
    _phone.font = [UIFont systemFontOfSize:17];
    _phone.clearButtonMode = UITextFieldViewModeWhileEditing;
    _phone.keyboardType = UIKeyboardTypeNumberPad;
    _phone.placeholder = @"请输入手机号";
    _phone.delegate = self;
    UIView *view3 = [[UIView alloc]init];
    view3.backgroundColor = WHITE;
    [self.view addSubview:view3];
    [view3 lt_Top:SunEdgesMake(0, 0, 0, Y(50)) to:view2 save:YES];
    UIImageView *img3 = [Sun copyWithView:img1];
    img3.image = [UIImage imageNamed:@"address_3"];
    [view3 addSubview:img3];
    [img3 lt_YcenterTo:nil save:YES];
    [img3 lt_setLeft:X(15) to:nil save:YES];
    _citys = [[UITextField alloc]init];
    [view3 addSubview:_citys];
    [_citys lt_YcenterTo:nil save:YES];
    [_citys lt_setLeft:X(50) to:nil save:YES];
    [_citys lt_setWidth:X(300) save:YES];
    _citys.textColor = BLACK;
    _citys.font = [UIFont systemFontOfSize:17];
    _citys.placeholder = @"请选择省市区";
    _citys.delegate = self;
    _citys.inputView = [self addressPickerView];
    UIView *view4 = [[UIView alloc]init];
    view4.backgroundColor = WHITE;
    [self.view addSubview:view4];
    [view4 lt_Top:SunEdgesMake(0, 0, 0, Y(50)) to:view3 save:YES];
    UIImageView *img4 = [Sun copyWithView:img1];
    img4.image = [UIImage imageNamed:@"address_4"];
    [view4 addSubview:img4];
    [img4 lt_YcenterTo:nil save:YES];
    [img4 lt_setLeft:X(15) to:nil save:YES];
    _area = [[UITextField alloc]init];
    [view4 addSubview:_area];
    [_area lt_YcenterTo:nil save:YES];
    [_area lt_setLeft:X(50) to:nil save:YES];
    [_area lt_setWidth:X(300) save:YES];
    _area.textColor = BLACK;
    _area.font = [UIFont systemFontOfSize:17];
    _area.placeholder = @"请选择街道";
    _area.delegate = self;
    _area.inputView = _areaPiker;
    UIView *view5 = [[UIView alloc]init];
    view5.backgroundColor = WHITE;
    [self.view addSubview:view5];
    [view5 lt_Top:SunEdgesMake(0, 0, 0, Y(100)) to:view4 save:YES];
    UIImageView *img5 = [Sun copyWithView:img1];
    img5.image = [UIImage imageNamed:@"address_5"];
    [view5 addSubview:img5];
    [img5 lt_setTop:Y(12) to:nil save:YES];
    [img5 lt_setLeft:X(15) to:nil save:YES];
    _detail = [[UITextView alloc] init];
    [view5 addSubview:_detail];
    [_detail lt_YcenterTo:nil save:YES];
    [_detail lt_setLeft:X(45) to:nil save:YES];
    [_detail lt_setWidth:X(300) save:YES];
    [_detail lt_setHeight:Y(100) save:YES];
    _detail.scrollEnabled = NO;
    _detail.editable = YES;
    _detail.delegate = self;
    _detail.textColor = [HXColor colorWithHexString:@"C7C7CD"];
    _detail.font = [UIFont systemFontOfSize:17];
    _detail.returnKeyType = UIReturnKeyDefault;
    _detail.keyboardType = UIKeyboardTypeDefault;
    _detail.textAlignment = NSTextAlignmentLeft;
    _detail.dataDetectorTypes = UIDataDetectorTypeAll;
    _detail.text = @"请输入您的详细地址";
    UIView *view6 = [[UIView alloc]init];
    view6.backgroundColor = WHITE;
    [self.view addSubview:view6];
    [view6 lt_Top:SunEdgesMake(Y(20), 0, 0, Y(50)) to:view5 save:YES];
    UIImageView *img6 = [Sun copyWithView:img1];
    img6.image = [UIImage imageNamed:@"address_6"];
    [view6 addSubview:img6];
    [img6 lt_YcenterTo:nil save:YES];
    [img6 lt_setLeft:X(15) to:nil save:YES];
    UIButton *btn1 = [[UIButton alloc]init];
    [view6 addSubview:btn1];
    [btn1 lt_YcenterTo:nil save:YES];
    [btn1 lt_setLeft:X(60) to:nil save:YES];
    [btn1 setTitle:@"家庭" forState:UIControlStateNormal];
    btn1.titleLabel.font = FONT(17);
    [btn1 setTitleEdgeInsets:UIEdgeInsetsMake(0, X(3), 0, -3)];
    [btn1 addTarget:self action:@selector(changeType:) forControlEvents:UIControlEventTouchUpInside];
    btn1.tag = 1;
    [btn1 setImage:[UIImage imageNamed:@"address_select"] forState:UIControlStateSelected];
    [btn1 setTitleColor:RED forState:UIControlStateSelected];
    [btn1 setImage:[UIImage imageNamed:@"address_default"] forState:UIControlStateNormal];
    [btn1 setTitleColor:BLACK forState:UIControlStateNormal];
    UIButton *btn2 = [[UIButton alloc]init];
    [view6 addSubview:btn2];
    [btn2 lt_YcenterTo:nil save:YES];
    [btn2 lt_setLeft:X(25) to:btn1 save:YES];
    [btn2 setTitle:@"公司" forState:UIControlStateNormal];
    btn2.titleLabel.font = FONT(17);
    [btn2 setTitleEdgeInsets:UIEdgeInsetsMake(0, X(3), 0, -3)];
    [btn2 addTarget:self action:@selector(changeType:) forControlEvents:UIControlEventTouchUpInside];
    btn2.tag = 2;
    [btn2 setImage:[UIImage imageNamed:@"address_select"] forState:UIControlStateSelected];
    [btn2 setTitleColor:RED forState:UIControlStateSelected];
    [btn2 setImage:[UIImage imageNamed:@"address_default"] forState:UIControlStateNormal];
    [btn2 setTitleColor:BLACK forState:UIControlStateNormal];
    
    UIView *view7 = [[UIView alloc]init];
    view7.backgroundColor = WHITE;
    [self.view addSubview:view7];
    [view7 lt_Top:SunEdgesMake(Y(20), 0, 0, Y(50)) to:view6 save:YES];
//    UIImageView *img7 = [Sun copyWithView:img1];
//    [view7 addSubview:img7];
//    [img7 lt_YcenterTo:nil save:YES];
//    [img7 lt_setLeft:X(15) to:nil save:YES];
    UILabel *la = [[UILabel alloc]init];
    [view7 addSubview:la];
    [la lt_YcenterTo:nil save:YES];
    [la lt_setLeft:X(40) to:nil save:YES];
    [la lt_setWidth:X(200) save:YES];
    la.textColor = BLACK;
    la.font = [UIFont systemFontOfSize:17];
    la.text = @"设为默认";
    _default = [[UISwitch alloc]init];
    [view7 addSubview:_default];
    [_default lt_YcenterTo:nil save:YES];
    [_default lt_setRight:X(30) to:nil save:YES];
    
    UIView *line1 = [[UIView alloc]init];
    line1.backgroundColor = LINE;
    [view1 addSubview:line1];
    [line1 lt_Top:SunEdgesMake(0, 0, 0, 0.5) to:nil save:YES];
    UIView *line2 = [Sun copyWithView:line1];
    [view1 addSubview:line2];
    [line2 lt_Bottom:SunEdgesMake(X(50), 0, 0, 0.5) to:nil save:YES];
    UIView *line3 = [Sun copyWithView:line1];
    [view2 addSubview:line3];
    [line3 lt_Bottom:SunEdgesMake(X(50), 0, 0, 0.5) to:nil save:YES];
    UIView *line4 = [Sun copyWithView:line1];
    [view3 addSubview:line4];
    [line4 lt_Bottom:SunEdgesMake(X(50), 0, 0, 0.5) to:nil save:YES];
    UIView *line5 = [Sun copyWithView:line1];
    [view4 addSubview:line5];
    [line5 lt_Bottom:SunEdgesMake(X(50), 0, 0, 0.5) to:nil save:YES];
    UIView *line6 = [Sun copyWithView:line1];
    [view5 addSubview:line6];
    [line6 lt_Bottom:SunEdgesMake(0, 0, 0, 0.5) to:nil save:YES];
    UIView *line7 = [Sun copyWithView:line1];
    [view6 addSubview:line7];
    [line7 lt_Bottom:SunEdgesMake(0, 0, 0, 0.5) to:nil save:YES];
    UIView *line8 = [Sun copyWithView:line1];
    [view6 addSubview:line8];
    [line8 lt_Top:SunEdgesMake(0, 0, 0, 0.5) to:nil save:YES];
    UIView *line9 = [Sun copyWithView:line1];
    [view7 addSubview:line9];
    [line9 lt_Bottom:SunEdgesMake(0, 0, 0, 0.5) to:nil save:YES];
    UIView *line10 = [Sun copyWithView:line1];
    [view7 addSubview:line10];
    [line10 lt_Top:SunEdgesMake(0, 0, 0, 0.5) to:nil save:YES];
    
    btn1.selected = YES;
    _la = 1;
    if (_address) {
        _addressDic = [NSMutableDictionary dictionaryWithDictionary:@{@"provinceId":_address[@"province"],@"cityId":_address[@"city"],@"areaId":_address[@"district"],@"streetId":_address[@"street"]}];
        _name.text = _address[@"consignee"];
        _phone.text = _address[@"mobile"];
        _citys.text = _address[@"address1"];
        _area.text = _address[@"address2"];
        _detail.text = _address[@"address"];
        _detail.textColor = BLACK;
        if ([_address[@"labels"] isEqualToString:@"公司"]) {
            btn1.selected = NO;
            btn2.selected = YES;
            _la = 2;
        }
        if ([_address[@"is_default"] intValue] == 1) {
            _default.on = YES;
        }
        [self requestToArea];
    }
    
}

#pragma mark ---- action
- (void)changeType:(UIButton *)btn {
    if (btn.isSelected == NO) {
        btn.selected = YES;
        int tag = 3 - (int)btn.tag;
        UIButton *btn2 = (UIButton *)[self.view viewWithTag:tag];
        btn2.selected = NO;
        _la = (int)btn.tag;
    }
}

- (void)save {
    if (_name.text.length < 2) {
        [[Sun shareSun]showMsg:@"请输入姓名"];
    } else if (_phone.text.length < 11){
        [[Sun shareSun]showMsg:@"请输入正确的手机号"];
    } else if (_detail.text.length < 5){
        [[Sun shareSun]showMsg:@"请输入详细地址，不少于5个字"];
    } else {
        NSString *url = [NSString stringWithFormat:@"%@%@",KURL,API_EDITADDRESS];
        NSDictionary *dic = @{@"address":[_detail.text stringFromUTF8],@"city":_addressDic[@"cityId"],@"consignee":[_name.text stringFromUTF8],@"district":_addressDic[@"areaId"],@"id":_address?_address[@"id"]:@"",@"is_default":_default.isOn?@"1":@"0",@"labels":_la==1?[@"家庭" stringFromUTF8]:[@"公司" stringFromUTF8],@"mobile":_phone.text,@"province":_addressDic[@"provinceId"],@"street":_addressDic[@"streetId"]?_addressDic[@"streetId"]:@""};
        [HttpRequest postURL:url withParam:dic success:^(id requestDic, NSString *msg) {
            [self.navigationController popViewControllerAnimated:YES];
        } failure:^(NSString *errorInfo, int code) {
            [[Sun shareSun] showMsg:errorInfo];
        }];
    }
}


#pragma mark ---- request
- (void)requestToArea{
    NSString *url = [NSString stringWithFormat:@"%@%@",KURL,API_GETAREA];
    [HttpRequest postURL:url withParam:@{@"id":[_addressDic objectForKey:@"areaId"]} success:^(id requestDic, NSString *msg) {
        _areaArr = requestDic;
        if (_addressDic[@"streetId"]) {
            for (int i=0; i<_areaArr.count; i++) {
                if ([_areaArr[i][@"id"] intValue] == [_addressDic[@"streetId"] intValue]) {
                    [_areaPiker selectRow:i inComponent:0 animated:NO];
                }
            }
        } else {
            //            _addressDic[@"streetId"] = _areaArr[0][@"id"];
            //            _addressDic[@"street"] = _areaArr[0][@"name"];
            //            _area.text = _areaArr[0][@"name"];
        }
    } failure:^(NSString *errorInfo, int code) {
        [[Sun shareSun] showMsg:errorInfo];
    }];
}

#pragma mark ---- textview
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if (range.location>=40){
        return  NO;
    }
    if ([text isEqualToString:@"\n"]) {
        return NO;
    }else{
        return YES;
    }
}

- (void)textViewDidBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@"请输入您的详细地址"]) {
        textView.text = @"";
        textView.textColor = BLACK;
    }
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView {
    if (textView.text.length == 0) {
        textView.text = @"请输入您的详细地址";
        textView.textColor = [HXColor colorWithHexString:@"C7C7CD"];
    }
    return YES;
}

#pragma mark ---- textField
- (void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField == _citys) {
        [self requestToArea];
    }
}

#pragma mark ---- piker
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    if (!_addressDic[@"streetId"]) {
        if (_areaArr.count > 0) {
            [_addressDic setObject:_areaArr[0][@"name"] forKey:@"street"];
            [_addressDic setObject:_areaArr[0][@"id"] forKey:@"streetId"];
            _area.text = _areaArr[0][@"name"];
        }else {
            [_addressDic setObject:@"" forKey:@"street"];
            [_addressDic setObject:@"" forKey:@"streetId"];
            _area.text = @"";
        }
    }
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return _areaArr.count;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return _areaArr[row][@"name"];
}

#pragma mark - UIPickerViewDelegate
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (_areaArr.count > 0) {
        [_addressDic setObject:_areaArr[row][@"name"] forKey:@"street"];
        [_addressDic setObject:_areaArr[row][@"id"] forKey:@"streetId"];
        _area.text = _areaArr[row][@"name"];
    }else {
        [_addressDic setObject:@"" forKey:@"street"];
        [_addressDic setObject:@"" forKey:@"streetId"];
        _area.text = @"";
    }
}


#pragma mark ---- address
- (NSArray *)addressArray {
    if (!_cityArr) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"citys" ofType:@"txt"];
        NSString *string = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
        NSData *jsonData = [string dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
        _cityArr = [dic objectForKey:@"province"];
    }
    return _cityArr;
}

- (IDAddressPickerView *)addressPickerView {
    if (_picker == nil) {
        _picker = [[IDAddressPickerView alloc] init];
        _picker.dataSource = self;
        NSString *path = [[NSBundle mainBundle] pathForResource:@"citys" ofType:@"txt"];
        NSString *string = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
        NSData *jsonData = [string dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
        _cityArr = [dic objectForKey:@"province"];
        _picker.addressArray = _cityArr;
        if (_address) {
            [_picker setRow:_address];
        }
    }
    return _picker;
}

- (void)setData:(NSDictionary *)dic{
    _citys.text = [[dic objectForKey:@"province"]stringByAppendingString:[dic objectForKey:@"city"]];
    if ([dic objectForKey:@"area"]) {
        _citys.text = [_citys.text stringByAppendingString:[dic objectForKey:@"area"]];
    }
    _addressDic = [NSMutableDictionary dictionaryWithDictionary:dic];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
